package houxb.cn.smuser;

import cn.hutool.core.date.DateUtil;
import com.alibaba.excel.EasyExcel;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;

import java.io.File;
import java.io.IOException;
import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.concurrent.TimeUnit;

import static cn.hutool.core.date.DatePattern.PURE_DATETIME_FORMAT;

public class Script {
    private final static String LINE_SEPARATOR = System.lineSeparator();
    private final static String CONFIG_FILE_NAME = "config.properties";

    public static void main(String[] args) throws IOException, InterruptedException {
//        Properties prop = new Properties();
        final String fileName, stageId, cookies;
//        File file = new File(".\\" + CONFIG_FILE_NAME);
//        if (file.exists()) {
//            try (FileInputStream input = new FileInputStream(file)) {
//                prop.load(new InputStreamReader(input, StandardCharsets.UTF_8));
//            }
//        } else {
//            try (InputStream input = Script.class.getClassLoader().getResourceAsStream(CONFIG_FILE_NAME)) {
//                if (input == null) {
//                    throw new RuntimeException("配置文件未找到!");
//                }
//                prop.load(new InputStreamReader(input, StandardCharsets.UTF_8));
//            }
//        }
        // 读取属性（带默认值）
        fileName = "合肥人员";
        cookies = "ecologycluster=659fd25f00fac53726ba884e362e7fdc; __clusterSessionCookieName=868C73A9EC4B6F3D49F2F0368F546F65; __clusterSessionIDCookieName=6d16ef9b-abc1-4d08-8275-628da93e412e; loginidweaver=201693; languageidweaver=7; PD-H-SESSION-ID=1_4_1_jWuCp2oxBvAO34VkekVLJ4V647zPNyQnFp2oUpnX0qjATQMV; PD-ID=wgNESWSgMV4mDkb/soD21Bgmw5sAbaYxNcDGceCkPFTmkek7eWSOKTMmkc14FrrGco2t0osE6GKb8Df9KduC2BDKxVL2XWPcwBtNeLJjQDDFZaY02wZIczCSTwrFz3X/h1yFLiuqndvMcjnnuovz/0htAsNGKjlEO/OWekmw/oNjqeFBqf6/Q/3g9D23VNWXxP250+etCv0WTjhveoKDdalhFcrHufhWWEdG/bjMNOhBREGcrUUZLF/XfPaD7w7eUqg8jjCYrrTHue/iAN6CaaS/7NvSLKV9ZTr07ssaMRk=; PD-ECC=BAGs3DBsAgEBAgIBmgIBAAIBAAQABFsEAazcMFUCAQECBGgljpwEEXBvcnRhbC5kY2l0cy5jb20ABAZkY2l0cwAEDi9wa21zdm91Y2hmb3IAMB8CAQEwGjAYAgEBBAxwZC1lY2MtaHR0cAAwBQQDODAA!.dcits.com; extloginid=5da7c2c23decbfae41e3ee6ec132a163; JSESSIONID=6d16ef9b-abc1-4d08-8275-628da93e412e; ecology_JSessionid=6d16ef9b-abc1-4d08-8275-628da93e412e; __randcode__=50d35993-04a6-4e1e-9b60-8edae0b76ccc";
        System.out.println("接收到的参数如下：");
        System.out.println("  文件名称：" + fileName + " Cookies：" + cookies);
        export(fileName, cookies);
    }

    public static void export(String fileName, String cookie) throws IOException, InterruptedException {
        List<SMUser> entities = new ArrayList<>();
        for (int i = 1; true; i++) {
            System.out.println("==================正在导出第 " + i + " 页==================");
            // 1. 创建 HttpClient
            HttpClient client = HttpClient.newHttpClient();
            // 2. 创建 HttpRequest
            HttpRequest request = HttpRequest.newBuilder()
                    .header("Cookie", cookie)
                    .uri(URI.create("https://portal.dcits.com/mobile/plugin/hrmNew/search/CustomizeHrmResourceSearchResult.jsp?searchvalue=合肥&page=" + i))
                    .GET()
                    .build();
            // 3. 发送请求并获取响应
            HttpResponse<String> response = client.send(
                    request,
                    HttpResponse.BodyHandlers.ofString()
            );
            Document document = Jsoup.parse(response.body());
            Elements itemCard = document.select(".search-peop-alls .crew-list-record");
            if (itemCard.isEmpty()) {
                break;
            }
            for (Element ele : itemCard) {
                SMUser entity = new SMUser();
                entities.add(entity);
                Elements xxmcing = ele.select(".list-xxmcing .info-wrap .personInfo");
                entity.setUserName(try2Str(xxmcing, 0));
                entity.setLoginName(try2Str(xxmcing, 1));
                entity.setId(try2Str(xxmcing, 2));

                entity.setDept(try2Str(ele.select(".list-left .first-record"), 0));
                entity.setPosition(try2Str(ele.select(".list-left .second-record"), 0));

                Elements thirdRecord = ele.select(".list-right .third-record li");
                if (!thirdRecord.isEmpty()) {
                    entity.setPlatform(try2Str(thirdRecord.get(0).select("span"), 1));
                }
                if (thirdRecord.size() > 1) {
                    entity.setCostCenter(try2Str(thirdRecord.get(1).select("span"), 1));
                }
                if (thirdRecord.size() > 2) {
                    entity.setOther(try2Str(thirdRecord.get(2).select("span"), 1));
                }

                Elements fourthRecord = ele.select(".list-right .fourth-record li");
                if (!fourthRecord.isEmpty()) {
                    entity.setLandline(try2Str(fourthRecord.get(0).select("span"), 1));
                }
                if (fourthRecord.size() > 1) {
                    entity.setPhone(try2Str(fourthRecord.get(1).select("span"), 1));
                }
                if (fourthRecord.size() > 2) {
                    entity.setEmail(try2Str(fourthRecord.get(2).select("span"), 1));
                }
            }
            try {
                // 语义更清晰，直接指定时间单位
                TimeUnit.SECONDS.sleep(1);
            } catch (InterruptedException e) {
                e.printStackTrace();
                Thread.currentThread().interrupt();
            }
        }
        File file = new File("/home/xbhou/alm/" + fileName + "_" + DateUtil.format(new Date(), PURE_DATETIME_FORMAT) + ".xlsx");
        if (!file.exists()) {
            if (!file.createNewFile()) {
                System.out.println("文件（" + file.getAbsolutePath() + "）创建失败！");
                return;
            }
        }
        // 这里 需要指定写用哪个class去写，然后写到第一个sheet，名字为模板 然后文件流会自动关闭
        // 如果这里想使用03 则 传入excelType参数即可
        EasyExcel.write(file, SMUser.class).sheet("模板").doWrite(entities);
    }

    private static String try2Str(Elements elms, int index) {
        try {
            return elms.get(index).text();
        } catch (Exception ignored) {

        }
        return null;
    }
}